from datetime import datetime
from random import randint

from django.conf import settings
from django.shortcuts import render
from rest_framework import status, response
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from django_redis import get_redis_connection
from rest_framework_simplejwt.views import TokenObtainSlidingView

from .tasks import send_sms
from .models import User

from .serializers import UserRegisterModelSerializer, ForgetPasswordModelSerializer, UserDataModelSerializer, \
    UserDetailModelSerializer, MyTokenObtainPairSerializer
from renameImg import imgpath
from upAli import AliyunOss


# Create your views here.

# 用户注册
class UserApiView(CreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserRegisterModelSerializer


# 发送短信验证码，将60s,300s过期存入redis
class SMSAPIView(APIView):
    def get(self, request, mobile):
        redis = get_redis_connection('sms_code')
        interval = redis.ttl(f'interval_{mobile}')
        if interval != -2:
            return Response({'errmsg': f"请勿频繁操作，请过{interval}秒再次操作", 'interval': interval},
                            status=status.HTTP_400_BAD_REQUEST)
        code = randint(1000, 9999)
        # 从配置中提取信息
        time = settings.RONGLIANYUN.get('sms_expire')
        sms_interval = settings.RONGLIANYUN.get('sms_interval')
        tid = settings.RONGLIANYUN.get('reg_tid')
        send_sms.delay(mobile,send_me=code)
        # 开启管道与事务，提高性能
        pipe = redis.pipeline()
        pipe.multi()
        pipe.setex(f'sms_{mobile}', time, code)
        pipe.setex(f'interval_{mobile}', sms_interval, "_")
        pipe.execute()
        return Response({'errmsg': "OK"}, status=status.HTTP_200_OK)


# 检查手机号是否注册
class MobileAPIView(APIView):
    def get(self, request, mobile):
        if User.objects.filter(mobile=mobile).exists() or User.objects.filter(username=mobile).exists():
            return Response({'message': '手机号已注册！'}, status=status.HTTP_400_BAD_REQUEST)
        return Response({'message': '手机号可用！'}, status=status.HTTP_200_OK)


class ForgetPwdView(UpdateAPIView):
    serializer_class = ForgetPasswordModelSerializer
    lookup_field = 'mobile'
    queryset = User.objects.all()


class UserDataView(UpdateAPIView):
    permission_classes = (IsAuthenticated,)
    serializer_class = UserDataModelSerializer
    queryset = User.objects.all()


from rest_framework.views import APIView
from django.conf import settings
import os


class UploadLogoView(APIView):
    # 上传头像
    def post(self, request):
        # 获取文件对象
        file = request.data.get("file")
        # file.file  上传文件的字节流
        # file.name  上传文件的名字

        # 拼接路径
        # static_path : 该路径前后不能有斜杠  对拼接有影响
        # 将静态资源文件夹拼接到项目根目录
        name = imgpath()
        end_fix = file.name.split(".")[-1]
        if end_fix not in ['jpg', 'png', 'jpeg', 'webp']:
            return Response({"msg": "图片格式不正确"})
        imgPath = os.path.join(settings.STATIC_PATH, 'avatar/2024/' + name + "." + end_fix)

        # 保存图片
        # wb  以二进制形式写入
        with open(imgPath, "wb") as f:
            # 写入字节流
            f.write(file.file.read())
        AliyunOss().put_object_from_file(f'uploads/avatar/2024/{name}.{end_fix}', imgPath)
        os.remove(imgPath)
# https://luffycityzhang.oss-cn-fuzhou.aliyuncs.com/uploads/avatar/2024/meidu.png
#         with open('https://luffycityzhang.oss-cn-fuzhou.aliyuncs.com/uploads/avatar/2024/' + name + "." + end_fix,'wb') as f:
#             f.write(file.file.read())

        # 返回响应
        data = {
            "code": 200,
            'msg': "上传图片成功",
            'imgPath': name + "." + end_fix,
        }
        return Response(data)


class UserDetailView(RetrieveAPIView):
    serializer_class = UserDetailModelSerializer
    queryset = User.objects.all()


class MyTokenObtainSlidingView(TokenObtainSlidingView):
    serializer_class = MyTokenObtainPairSerializer
    queryset = User.objects.filter(is_active=True)





from django_oss_storage.backends import  OssMediaStorage
import  django.utils.encoding